package com.atguigu.flink.chapter11;

import com.atguigu.flink.chapter05.Source.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Over;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.Tumble;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.*;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/1/27 14:19
 */
public class Flink12_TableAPI_OverWindow {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .fromElements(
                        new WaterSensor("sensor_1", 1000L, 10),
                        new WaterSensor("sensor_1", 2000L, 20),
                        new WaterSensor("sensor_2", 3000L, 30),
                        new WaterSensor("sensor_1", 4000L, 40),
                        new WaterSensor("sensor_1", 5000L, 50),
                        new WaterSensor("sensor_2", 6000L, 60))
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                                .withTimestampAssigner((element, ts) -> element.getTs())
                );

        // 创建 表的 执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        Table sensorTable = tableEnv.fromDataStream(sensorDS, $("id"), $("ts").rowtime(), $("vc"));

        // TODO TableAPI 使用 OverWindow
        sensorTable
                .window(
                        Over
                                .partitionBy($("id"))
                                .orderBy($("ts"))
//                                .preceding(UNBOUNDED_RANGE)
//                                .preceding(UNBOUNDED_ROW)
//                                .following(CURRENT_ROW)
//                                .preceding(lit(3).seconds()) // 窗口的范围是，往前 3s
                                .preceding(rowInterval(2L)) // 窗口的范围是，往前 2行
                                .as("ow")
                )
                .select($("id"),
                        $("ts"),
                        $("vc"),
                        $("vc").sum().over($("ow")).as("vcSumByOver"))
                .execute()
                .print();


    }
}
/*

 */